package org.bim.view.drag.design.controller;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Splitter;
import org.bim.view.drag.design.api.dto.VisualDbDTO;
import org.bim.view.drag.design.api.req.VisualDbReq;
import org.bim.view.drag.design.dao.VisualDbMapper;
import org.bim.view.drag.design.entity.TVisualDb;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.bim.view.drag.design.model.HttpResult;
import org.bim.view.drag.design.model.Page;
import org.bim.view.drag.design.util.AssertUtil;
import org.bim.view.drag.design.util.PageUtil;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author bim-view
 * @date 2021/12/16 4:48 下午
 */
@Api
@Slf4j
@AllArgsConstructor
@RestController
@RequestMapping("db")
public class VisualDbController {
    private static final String AES_KEY = "O2BEeIv399qHQNhD6aGW8R8DEj4bqHXm"; // 和前端保持一致

    private VisualDbMapper visualDbMapper;

    @GetMapping("detail")
    public HttpResult<TVisualDb> detail(TVisualDb req) {
        return HttpResult.success(visualDbMapper.selectOne(req));
    }

    @GetMapping("list")
    public HttpResult<Page<TVisualDb>> page(VisualDbReq req) {
        Page<TVisualDb> page = PageUtil.doPage(req.toCondition(), () -> visualDbMapper.select(req.toEntity()));
        return HttpResult.success(page);
    }

    @PostMapping("save")
    public HttpResult<String> save(@RequestBody TVisualDb form) {
        visualDbMapper.insertSelective(form);
        return HttpResult.success(form.getId());
    }

    @PostMapping("update")
    public HttpResult<String> update(@RequestBody TVisualDb form) {
        visualDbMapper.updateByPrimaryKeySelective(form);
        return HttpResult.success(form.getId());
    }

    @PostMapping("submit")
    public HttpResult submit(@RequestBody TVisualDb form) {
        return Objects.nonNull(form.getId()) ? update(form) : save(form);
    }

    @Transactional
    @PostMapping("remove")
    public HttpResult remove(@RequestParam String ids) {
        Splitter.on(",").split(ids).forEach(id -> {
            TVisualDb entity = visualDbMapper.selectByPrimaryKey(id);
            AssertUtil.isTrue(Objects.nonNull(entity), "对象不存在");
            entity.setIsDeleted(true);
            visualDbMapper.updateByPrimaryKeySelective(entity);
        });
        return HttpResult.success();
    }

    @PostMapping("db-test")
    public HttpResult<Boolean> dbTest(@RequestBody String encryptData) {
        JSONObject jsonObject = decrypt(encryptData);
        TVisualDb db = JSONObject.parseObject(jsonObject.toJSONString(), TVisualDb.class);

        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(db.getUrl());
        dataSource.setUsername(db.getUsername());
        dataSource.setPassword(db.getPassword());
        dataSource.setDriverClassName(db.getDriverClass());
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        try {
            jdbcTemplate.execute("select 1");
            return HttpResult.success(true);
        } catch (Exception e) {
            if (log.isDebugEnabled()) {
                log.error("数据源连接测试发生错误：", e);
            }
            return HttpResult.success(false);
        }
    }

    @GetMapping("db-list")
    public HttpResult<List<VisualDbDTO>> dbList() {
        List<VisualDbDTO> list = visualDbMapper.selectAll().stream()
                .map(db -> new VisualDbDTO(db.getId(), db.getName(), db.getDriverClass()))
                .collect(Collectors.toList());

        return HttpResult.success(list);
    }

    @PostMapping("dynamic-query")
    public HttpResult<Object> dynamicQuery(@RequestBody String encryptData) {
        JSONObject jsonObject = decrypt(encryptData);
        String id = jsonObject.getString("id");
        String sql = jsonObject.getString("sql");
        if (StringUtils.isEmpty(id)||StringUtils.isEmpty(sql)) {
            return HttpResult.success();
        }

        TVisualDb db = visualDbMapper.selectByPrimaryKey(id);
        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(db.getUrl());
        datasource.setUsername(db.getUsername());
        datasource.setPassword(db.getPassword());
        datasource.setDriverClassName(db.getDriverClass());
        JdbcTemplate jdbcTemplate = new JdbcTemplate(datasource);
        try {
            List<Map<String, Object>> data = jdbcTemplate.queryForList(sql);
            return HttpResult.success(data);
        } catch (DataAccessException e) {
            String msg = e.getMessage();
            return HttpResult.fail("数据访问异常, msg: " + msg);
        }
    }

    private JSONObject decrypt(String encryptData) {
        byte[] data = SecureUtil.aes(AES_KEY.getBytes(StandardCharsets.UTF_8)).decrypt(encryptData);
        return JSONObject.parseObject(new String(data));
    }
}
